package com.atqinke.algorithm;

/**
 * @BelongsProject: BasicConnection
 * @BelongsPackage: com.atqinke.algorithm
 * @Author: NieHk
 * @CreateTime: 2022-08-16  16:21
 * @Description: 冒泡算法
 * @Version: 1.0
 */
public class Bubbling {
    public static void main(String[] args) {
        int[] array = new int[]{6, 5, 4, 3, 2, 1};
        bubblingSort(array);
        for (int i : array) {
            System.out.print(i);
        }
        System.out.println("");
        int[] newArray = new int[]{7, 45, 6, 5, 4, 3, 2, 1};
        bubblingSort(newArray, newArray.length);
        for (int i : newArray) {
            System.out.print(i + ",");
        }
    }


    /**
     * 冒泡排序
     *
     * @param array
     */
    public static void bubblingSort(int[] array) {
        int length = array.length - 1;
        for (int i = 0; i < length; i++) {
            for (int j = 0; j < length - i; j++) {
                if (array[j] > array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
    }

    /**
     * 递归算法实现冒泡排序
     *
     * @param array
     * @param n
     */
    public static void bubblingSort(int[] array, int n) {
        if (n == 1) {
            return;
        }
        if (array == null || array.length == 0) {
            return;
        }
        for (int i = 0; i < n - 1; i++) {
            if (array[i] > array[i + 1]) {
                int temp = array[i];
                array[i] = array[i + 1];
                array[i + 1] = temp;
            }
        }
        bubblingSort(array, n - 1);
    }
}
